package com.example.universitylibraryback.service;

import com.example.universitylibraryback.dto.BookDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.List;

@Service
public class CacheService {
    private final RedisTemplate<String, Object> redisTemplate;
    
    @Autowired
    public CacheService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    
    // 缓存单本图书信息
    public void cacheBookInfo(BookDTO book) {
        String key = "book:" + book.getBookId();
        redisTemplate.opsForValue().set(key, book, Duration.ofHours(1));
    }
    
    // 获取缓存的图书信息
    public BookDTO getCachedBookInfo(String bookId) {
        String key = "book:" + bookId;
        return (BookDTO) redisTemplate.opsForValue().get(key);
    }
    
    // 缓存热门图书列表
    public void cacheHotBooks(List<BookDTO> books) {
        String key = "hot:books";
        redisTemplate.opsForValue().set(key, books, Duration.ofMinutes(30));
    }
    
    // 获取缓存的热门图书
    public List<BookDTO> getCachedHotBooks() {
        String key = "hot:books";
        return (List<BookDTO>) redisTemplate.opsForValue().get(key);
    }
    
    // 缓存可借图书列表
    public void cacheAvailableBooks(List<BookDTO> books) {
        String key = "available:books";
        redisTemplate.opsForValue().set(key, books, Duration.ofMinutes(15));
    }
    
    // 获取缓存的可借图书
    public List<BookDTO> getCachedAvailableBooks() {
        String key = "available:books";
        return (List<BookDTO>) redisTemplate.opsForValue().get(key);
    }
    
    // 删除图书缓存
    public void removeBookCache(String bookId) {
        String key = "book:" + bookId;
        redisTemplate.delete(key);
    }
    
    // 删除图书相关的所有缓存
    public void clearBookRelatedCache() {
        redisTemplate.delete("hot:books");
        redisTemplate.delete("available:books");
    }
}